<?php

namespace app\admin\controller;

use Alipay\EasySDK\Kernel\Factory as alipayFactory;
use aop\AlipayConfig;
use aop\AopCertClient;
use aop\request\AlipayFundTransUniTransferRequest;
use app\api\model\CarCate;
use app\api\model\OrderChange;
use app\api\model\OrderContinue;
use app\api\model\OrderFace;
use app\common\controller\Backend;
use app\common\model\PlatformLog;
use app\common\model\User;
use EasyWeChat\Factory;
use think\facade\Config;
use app\common\model\Order as OrderModel;
use app\common\model\MerchantCar;
use think\facade\Db;
use think\Model;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    protected $relationSearch = true;
    /**
     * Order模型对象
     * @var \app\common\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order;
        $refundStatusList = \app\common\model\Order::fetchRefundStatus();
        $changeStatusList = \app\common\model\Order::fetchChangeStatus();
        $continueStatusList = \app\common\model\Order::fetchContinueStatus();
        $faceStatusList = \app\common\model\Order::fetchFaceStatus();
        $orderRefundStatusList = \app\common\model\Order::fetchOrderRefundStatus();
        $group_id = $this->group_id;
        $this->view->assign(['refundStatusList' => $refundStatusList, 'changeStatusList' => $changeStatusList, 'continueStatusList' => $continueStatusList, 'faceStatusList' => $faceStatusList, 'orderRefundStatusList' => $orderRefundStatusList, 'group_id' => $group_id]);
        $this->assignconfig(['refundStatusList' => $refundStatusList, 'changeStatusList' => $changeStatusList, 'continueStatusList' => $continueStatusList, 'faceStatusList' => $faceStatusList, 'orderRefundStatusList' => $orderRefundStatusList, 'group_id' => $group_id]);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看.
     */
    public function index()
    {
        $user_id = request()->param('user_id');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter");
            $op = $this->request->get("op");
            $tempFilter = json_decode($filter, true) ?? [];
            $tempOp = json_decode($op, true) ?? [];
            $username = '';
            if(isset($tempFilter['username'])){
                $username = $tempFilter['username'];
                unset($tempFilter['username']);
                unset($tempOp['username']);
                $filter = json_encode($tempFilter);
                $op = json_encode($tempOp);
            }
            $pick_address = '';
            if(isset($tempFilter['pick_address'])){
                $pick_address = $tempFilter['pick_address'];
                unset($tempFilter['pick_address']);
                unset($tempOp['pick_address']);
                $filter = json_encode($tempFilter);
                $op = json_encode($tempOp);
            }
            $merchant_car_name = '';
            if(isset($tempFilter['merchant_car_name'])){
                $merchant_car_name = $tempFilter['merchant_car_name'];
                unset($tempFilter['merchant_car_name']);
                unset($tempOp['merchant_car_name']);
                $filter = json_encode($tempFilter);
                $op = json_encode($tempOp);
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams(null, null, $filter, $op);
            $builder = $this->model;
            if($user_id){
                $builder->where('user_id', $user_id);
            }
            if($this->group_id == 2 && $this->merchant){
                $builder->where('order.merchant_id', $this->merchant['id']);
            }
            if($username){
                $user_id = User::where('username', 'like', '%'.$username.'%')->column('id');
                $user_id = $user_id ? implode(',', $user_id) : '';
                $builder->where("order.user_id in ($user_id) or order.user_phone like %$username%");
            }
            if($merchant_car_name){
                $builder->where("order.merchant_car_name like %$merchant_car_name% or order.car_number like %$merchant_car_name%");
            }
            if($pick_address){
                $builder->where("order.pick_address like %$pick_address% or order.return_address like %$pick_address%");
            }
            $total = $builder
                ->withJoin(['user'])
                ->with(['order_change_pay', 'order_change_unpay', 'order_continue_pay', 'order_continue_unpay', 'order_face_pay', 'order_face_unpay'])
//                ->withCount(['order_continue', 'order_change', 'order_face'])
                ->where($where)
                ->where('order.is_delete', 1)
                ->whereIn('order.status', '1,2,3,4')
                ->order($sort, $order)
                ->count();
            $list  = $builder
                ->withJoin(['user' => ['id','username','truename','mobile','id_card']])
                ->with(['order_change_pay', 'order_change_unpay', 'order_continue_pay', 'order_continue_unpay', 'order_face_pay', 'order_face_unpay', 'order_continue', 'order_change', 'order_face'])
                ->where($where)
                ->where('order.is_delete', 1)
                ->whereIn('order.status', '1,2,3,4')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as &$value){
                $value->change_num = $value->order_change->count();
                $value->continue_num = $value->order_continue->count();
                $value->face_num = $value->order_face->count();
                $value['cancel_time'] = $value['cancel_time'] ? date('Y-m-d H:i:s', $value['cancel_time']) : '';
                $value['cancel_type'] = \app\api\model\Order::fetchCancelType($value['cancel_type']);
//                if($value->continue->toArray()){
//                    $continue_end_time = $value->continue->column('end_time');
//                    rsort($continue_end_time);
//                    $value->end_time = $continue_end_time[0];
//                }

                $all_money = $value['all_money'];
//                if($value['order_change_pay']->toArray()){
//                    $change_money_list = $value->order_change_pay->column('diff_money');
//                    $change_money = array_sum($change_money_list);
//                    $all_money = bcadd($all_money, $change_money, 2);
//                }
                if($value['order_change_pay']->toArray()){
                    $change_money_list = array_column($value['order_change_pay']->toArray(), 'diff_money');
                    $change_money = array_sum($change_money_list);
                    $all_money = bcadd($all_money, $change_money, 2);
                    $change_car_ids = [];
                    $change_car_prices = [];
                    foreach ($value['order_change_pay'] as $ks=>$vs){
                        if($vs['merchant_car_id']){
                            $change_car_ids[] = $vs['merchant_car_id'];
                        }
                        if($vs['price']){
                            $change_car_prices[] = $vs['price'];
                        }
                    }
                    if($change_car_ids){
                        $value['merchant_car_id'] = $change_car_ids[0];
                        $new_merchant_car = MerchantCar::field('car_id,merchant_car_name,car_price')->with('cars')->where('id', $value['merchant_car_id'])->find();
                        $value['car_name'] = $new_merchant_car['car_name'];
                        $value['car_image'] = $new_merchant_car['car_image'];
                        $value['merchant_car_name'] = $new_merchant_car['merchant_car_name'];
                    }
                    if($change_car_prices){
                        $value['price'] = $change_car_prices[0];
                    }
                    if($value['order_change_pay'][0]['other_number']){
                        $value['car_number'] = $value['order_change_pay'][0]['other_number'];
                    }else{
                        $value['car_number'] = MerchantCar::where('id', $value['order_change_pay'][0]['merchant_car_id'])->value('car_number');
                    }
                }
                if($value['order_continue_pay']->toArray()){
                    $continue_money_list = $value->order_continue_pay->column('all_money');
                    $continue_money = array_sum($continue_money_list);
                    $all_money = bcadd($all_money, $continue_money, 2);
                    $value['end_time'] = $value['order_continue_pay'][0]['end_time'];
                }
                if($value['order_face_pay']->toArray()){
                    $face_money_list = $value->order_face_pay->column('all_money');
                    $face_money = array_sum($face_money_list);
                    $all_money = bcadd($all_money, $face_money, 2);
                }
                $value['face_money'] = $face_money??0;
                $value['all_money'] = $all_money;
                $res = getDhir($value->start_time, $value->end_time);
                if($res['d'] > 0){
                    $days_new = $res['h'] > 0 ? $res['d'] . '天' . $res['h'] . '小时' : $res['d'] . '天';
                }else{
                    $days_new = $res['h'] . '小时';
                }
                $value['days'] = $days_new;
                $value['start_time'] = date('Y-m-d H:i', $value['start_time']);
                $value['end_time'] = date('Y-m-d H:i', $value['end_time']);
            }
            $result = ['total' => $total, 'rows' => $list];

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model
            ->with(['users','order_change_pay'])
            ->field('id,out_trade_no,user_id,merchant_id,merchant_car_id,start_time,end_time,days,rental_money,deposit,pick_fee,night_pick_fee,night_return_fee,return_fee,all_money,status,deposit_status,send_type,car_name,car_number,car_image,car_label,car_note,shop_name,shop_logo,shop_address,shop_phone,driver_name,driver_number,coupon_money,createtime,user_phone,insurance,insurance_id,pay_type,deposit_type,driver_idcard_face,driver_idcard_back,driver_license_face,driver_license_back,start_dashboard,end_dashboard,start_check_video,end_check_video,start_check_images,end_check_images,end_confirm,start_note,pick_time,end_note,return_time,rental_contract,real_return_time,offline_money,offline_note,liquidated_damages,handle_fee,change_status,continue_status,face_status,pick_address,return_address,transaction_id,time_end,refund_money,refund_id,refund_time,total_fee,refund_time,driver_idcard_face,driver_idcard_back,driver_license_face,driver_license_back,start_dashboard,end_dashboard,start_check_video,end_check_video,start_check_images,end_check_images,start_note,pick_time,end_note,rental_contract,liquidated_damages,handle_fee,all_change_refund_money,cancel_time,cancel_reason,cancel_type,all_change_refund_money,refund_status,order_refund_status,order_refund_money,order_refund_type,order_refund_note')
            ->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if($row){
            $row['cancel_time'] = $row['cancel_time'] ? date('Y-m-d H:i:s', $row['cancel_time']) : '';
            $row['cancel_type'] = \app\common\model\Order::fetchCancelType($row['cancel_type']);
            $order_continue = \app\admin\model\OrderContinue::where(['is_delete' => 1, 'order_id' => $ids, 'pay_status' => ['in', '1,2'], 'continue_status' => ['in', '1,2']])->column('end_time');
            if($order_continue){
                rsort($order_continue);
                $row['end_time'] = $order_continue[0];
            }
            //如果有换车订单 租赁费用 保险费用 手续费 总价 重新计算显示
            if($row['order_change_pay']){
                $all_money = $row['all_money'];
                $change_money_list = array_column($row['order_change_pay'], 'diff_money');
                $change_money = array_sum($change_money_list);
                $all_money = bcadd($all_money, $change_money, 2);
                $row['all_money'] = $all_money;
                $change_car_ids = [];
                $change_car_prices = [];
                $change_car_rentals = [];
                $change_car_deposits = [];
                $change_car_handles = [];
                foreach ($row['order_change_pay'] as $ks=>$vs){
                    if($vs['merchant_car_id']){
                        $change_car_ids[] = $vs['merchant_car_id'];
                    }
                    if($vs['price']){
                        $change_car_prices[] = $vs['price'];
                    }
                    if($vs['rental_money']){
                        $change_car_rentals[] = $vs['rental_money'];
                    }
                    if($vs['deposit']){
                        $change_car_deposits[] = $vs['deposit'];
                    }
                    if($vs['handle_fee']){
                        $change_car_handles[] = $vs['handle_fee'];
                    }
                }
                if($change_car_ids){
                    $row['merchant_car_id'] = $change_car_ids[0];
                    $new_merchant_car = MerchantCar::field('car_id,merchant_car_name,car_price,drive,displacement')->with('cars')->where('id', $row['merchant_car_id'])->find();
                    $row['car_name'] = $new_merchant_car['car_name'];
                    $row['car_image'] = $new_merchant_car['car_image'];
//                    $row['merchant_car_name'] = $new_merchant_car['merchant_car_name'];
                    $car_gear = $new_merchant_car['car_gear'] == 1 ? '手动' : '自动';
                    $row['car_label'] = $new_merchant_car['car_site'].'座|'.$new_merchant_car['car_gate'].'门|'.$car_gear.'|'.$new_merchant_car['displacement'];
                }
                if($change_car_prices){
                    $row['price'] = $change_car_prices[0];
                }
                if($change_car_rentals){
                    $row['rental_money'] = $change_car_rentals[0];
                }
                if($change_car_deposits){
                    $row['deposit'] = $change_car_deposits[0];
                }
                if($change_car_handles){
                    $row['handle_fee'] = $change_car_handles[0];
                }
                if($row['order_change_pay'][0]['other_number']){
                    $row['car_number'] = $row['order_change_pay'][0]['other_number'];
                }else{
                    $row['car_number'] = MerchantCar::where('id', $row['order_change_pay'][0]['merchant_car_id'])->value('car_number');
                }
            }
            $row['change_status'] = \app\admin\model\Order::fetchChangeStatus($row['change_status']);
            $row['continue_status'] = \app\admin\model\Order::fetchContinueStatus($row['continue_status']);
            $row['face_status'] = \app\admin\model\Order::fetchFaceStatus($row['face_status']);
            $res = getDhir($row['start_time'], $row['end_time']);
            if($res['d'] > 0){
                $days_new = $res['h'] > 0 ? $res['d'] . '天' . $res['h'] . '小时' : $res['d'] . '小时';
            }else{
                $days_new = $res['h'] . '小时';
            }
            $row['days'] = $days_new;

            if($row['send_type'] == 1){
                unset($row['address_name'],$row['address_phone'],$row['address_street']);
            }else{
                unset($row['user_phone']);
            }
            $row['status'] = $row['status_text'];
            $row['send_type'] = $row['send_type_text'];
            $row['createtime'] = $row['createtime_text'];
            $row['start_time'] = date('Y-m-d H:i:s', $row['start_time']);
            $row['end_time'] = date('Y-m-d H:i:s', $row['end_time']);
            $row['time_end'] = $row['time_end'] ? date('Y-m-d H:i:s', $row['time_end']) : '';
            if($row['deposit'] > 0){
                $row['deposit_status'] = $row['deposit_status_text'];
            }
            if($row['status'] == 4){
                $row['refund_time'] = $row['refund_time_text'];
            }else{
                unset($row['refund_time'],$row['refund_money'],$row['refund_id']);
            }
            $row['insurance_id'] = \app\admin\model\MerchantCarInsure::where('id', $row['insurance_id'])->value('insure_name');
            $row['pay_type'] = \app\common\model\Order::fetchPayType($row['pay_type']);
            $row['deposit_type'] = \app\common\model\Order::fetchDepositType($row['deposit_type']);
            $row['start_check_images'] = $row['start_check_images'] ? explode(',', $row['start_check_images']) : [];
            $row['end_check_images'] = $row['end_check_images'] ? explode(',', $row['end_check_images']) : [];
            $row['end_confirm'] = $row['end_confirm'] ? explode(',', $row['end_confirm']) : [];
            $row['rental_contract'] = $row['rental_contract'] ? explode(',', $row['rental_contract']) : [];
            $row['pick_time'] = $row['pick_time'] ? date('Y-m-d H:i:s', $row['pick_time']) : '';
            $row['return_time'] = $row['return_time'] ? date('Y-m-d H:i:s', $row['return_time']) : '';
            $row['real_return_time'] = $row['real_return_time'] ? date('Y-m-d H:i:s', $row['real_return_time']) : '';
            $row['refund_status'] = \app\common\model\Order::fetchRefundStatus($row['refund_status']);
            $row['order_refund_status'] = \app\common\model\Order::fetchOrderRefundStatus($row['order_refund_status']);
            $row['order_refund_type'] = \app\admin\model\RefundType::where('id', $row['order_refund_type'])->value('name');
            unset($row['id'],$row['order_change_pay'],$row['createtime_text'],$row['start_time_text'],$row['end_time_text'],$row['send_type_text'],$row['time_end_text'],$row['status_text'],$row['deposit_status_text'],$row['refund_time_text'],$row['user_id'],$row['merchant_id'],$row['merchant_car_id']);
        }
//        dump($row);die;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where('id', 'in', $ids)->update(['is_delete' => 2, 'deletetime' => time()]);
        $this->success();
    }

    /**
     * 取消订单
     */
    public function cancel()
    {
        $ids = $this->request->param('ids');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->with(['order_change_payed', 'order_continue_payed', 'order_face_payed'])->where('id', 'in', $ids)->select();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $config = \app\api\model\Config::where('name', 'in', 'cancel_time1,cancel_money1,cancel_money2')->column('value', 'name');
        $cancel_rate = 0;//扣款比例
        $cancel_time = $config['cancel_time1']*3600;
        foreach ($row as $val){
            if($val['status'] != 1){
                $this->error(__('有非已预约状态的订单'));
            }
            if(time() - $val['time_end'] > 86400*365){
                $this->error(__('有订单支付时间超过一年'));
            }
        }
        Db::startTrans();
        try {
            $user_model = new User();
            $platform_log = [];
            foreach ($row as $ky=>$vue){
                $user = User::where('id', $vue['user_id'])->find();
                $order = $vue;
                //判断是否扣款
                if(time() + $cancel_time >= $vue['start_time'] && time() + $cancel_time <= $vue['start_time']){
                    $cancel_rate = $config['cancel_money1'] / 100;
                }elseif(time() > $vue['start_time']){
                    $cancel_rate = $config['cancel_money2'] / 100;
                }

                if($cancel_rate < 1){
                    if($order['pay_type'] == 1){//微信
                        //主订单退款
                        $liquidated_damages = bcmul($cancel_rate, $order['last_all_money'], 2);
                        $refund_money = bcsub($order['last_all_money'], $liquidated_damages, 2);
                        $order['refund_money'] = $refund_money;
                        $update = ['status' => 4, 'cancel_time' => time()];
                        if($order['deposit_status'] == 1 && $order['deposit'] > 0){
                            $update['deposit_status'] = 2;
                        }
                        $out_refund_no = $this->getOutRefundNo();
                        $order['out_refund_no'] = $out_refund_no;
                        $res = $this->wechatRefund($order, $user, 1);
                        if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                            $update['out_refund_no'] = $out_refund_no;
                            $update['refund_id'] = $res['refund_id'];
                            $update['refund_time'] = time();
                            $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                            $update['liquidated_damages'] = $liquidated_damages;
                            $all_refund_money = bcadd($order['all_refund_money'], $refund_money, 2);
                            $last_all_money = bcsub($order['last_all_money'], $refund_money, 2);
                            if($last_all_money < 0) $last_all_money = 0;
                            if($all_refund_money > $order['all_money']) $all_refund_money = $order['all_money'];
                            $update['all_refund_money'] = $all_refund_money;
                            $update['last_all_money'] = $last_all_money;
                            $update['all_refund_number'] = $order['all_refund_number'] ? $order['all_refund_number'] . ',' . $out_refund_no : $out_refund_no;
                            $result = $this->model->where('id', $order['id'])->update($update);
                            //车状态修改
                            MerchantCar::where('id', $order['merchant_car_id'])->update(['car_status' => 1]);
                            //写入平台流水
                            $platform_log = [
                                'user_id' => $user['id'],
                                'amount' => $order['all_money'],
                                'type' => 3,
                                'log_note' => '取消预约退款',
                                'order_id' => $order['id'],
                                'order_type' => 2,
                                'createtime' => time(),
                                'total_order_id' => $order['id']
                            ];
                            \app\common\model\PlatformLog::insert($platform_log);
                        }else{
                            Db::rollback();
                            $this->error('取消失败');
                        }

                        //换车订单退款
                        $order_change_payed = $order['order_change_payed'];
                        if($order_change_payed){
                            foreach ($order_change_payed as $key=>$value){
                                $liquidated_damages = bcmul($cancel_rate, $value['last_all_money'], 2);
                                $refund_money = bcsub($value['last_all_money'], $liquidated_damages, 2);
                                $value['refund_money'] = $refund_money;
                                $update = ['pay_status' => 3, 'cancel_time' => time()];
                                if($value['deposit_status'] == 1 && $value['deposit'] > 0){
                                    $update['deposit_status'] = 2;
                                }
                                $out_refund_no = $this->getOutRefundNo('order_change');
                                $value['out_refund_no'] = $out_refund_no;
                                $res = $this->wechatRefund($value, $user);
                                if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['refund_id'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                    $update['liquidated_damages'] = $liquidated_damages;
                                    $result = \app\admin\model\OrderChange::where('id', $value['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $value['refund_money'],
                                        'type' => 7,
                                        'log_note' => '取消预约换车订单退款',
                                        'order_id' => $value['id'],
                                        'order_type' => 2,
                                        'createtime' => time(),
                                        'total_order_id' => $order['id']
                                    ];
                                    \app\common\model\PlatformLog::insert($platform_log);
                                }else{
                                    Db::rollback();
                                    $this->error('取消失败');
                                }
                            }
                        }

                        //续租订单退款
                        $order_continue_payed = $order['order_continue_payed'];
                        if($order_continue_payed){
                            foreach ($order_continue_payed as $k=>$v){
                                $liquidated_damages = bcmul($cancel_rate, $v['last_all_money'], 2);
                                $refund_money = bcsub($v['last_all_money'], $liquidated_damages, 2);
                                $v['refund_money'] = $refund_money;
                                $update = ['pay_status' => 3, 'cancel_time' => time()];
                                if($v['deposit_status'] == 1 && $v['deposit'] > 0){
                                    $update['deposit_status'] = 2;
                                }
                                $out_refund_no = $this->getOutRefundNo('order_continue');
                                $v['out_refund_no'] = $out_refund_no;
                                $res = $this->wechatRefund($v, $user);
                                if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['refund_id'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                    $update['liquidated_damages'] = $liquidated_damages;
                                    $result = \app\admin\model\OrderContinue::where('id', $v['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $v['refund_money'],
                                        'type' => 9,
                                        'log_note' => '取消预约续租订单退款',
                                        'order_id' => $v['id'],
                                        'order_type' => 2,
                                        'createtime' => time(),
                                        'total_order_id' => $order['id']
                                    ];
                                    \app\common\model\PlatformLog::insert($platform_log);
                                }else{
                                    Db::rollback();
                                    $this->error('取消失败');
                                }
                            }
                        }

                        //当面付订单退款
                        $order_face_payed = $order['order_face_payed'];
                        if($order_face_payed){
                            foreach ($order_face_payed as $kk=>$vv){
                                $liquidated_damages = bcmul($cancel_rate, $vv['last_all_money'], 2);
                                $refund_money = bcsub($vv['last_all_money'], $liquidated_damages, 2);
                                $vv['refund_money'] = $refund_money;
                                $update = ['pay_status' => 3, 'cancel_time' => time()];
                                if($vv['deposit_status'] == 1 && $vv['deposit'] > 0){
                                    $update['deposit_status'] = 2;
                                }
                                $out_refund_no = $this->getOutRefundNo('order_face');
                                $vv['out_refund_no'] = $out_refund_no;
                                $res = $this->wechatRefund($vv, $user);
                                if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['refund_id'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                    $update['liquidated_damages'] = $liquidated_damages;
                                    $result = \app\admin\model\OrderFace::where('id', $vv['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $vv['refund_money'],
                                        'type' => 11,
                                        'log_note' => '取消预约当面付订单退款',
                                        'order_id' => $vv['id'],
                                        'order_type' => 2,
                                        'createtime' => time(),
                                        'total_order_id' => $order['id']
                                    ];
                                    \app\common\model\PlatformLog::insert($platform_log);
                                }else{
                                    Db::rollback();
                                    $this->error('取消失败');
                                }
                            }
                        }
                    }else{//支付宝
                        //主订单退款
                        $liquidated_damages = bcmul($cancel_rate, $order['last_all_money'], 2);
                        $refund_money = bcsub($order['last_all_money'], $liquidated_damages, 2);
                        $order['refund_money'] = $refund_money;
                        $update = ['status' => 4, 'cancel_time' => time()];
                        if($order['deposit_status'] == 1 && $order['deposit'] > 0){
                            $update['deposit_status'] = 2;
                        }
                        $out_refund_no = $this->getOutRefundNo();
                        $order['out_refund_no'] = $out_refund_no;
                        $res = $this->alipayRefund($order, $user);
                        if($res['code'] == '10000'){
                            $update['out_refund_no'] = $order['out_refund_no'];
                            $update['refund_id'] = $res['trade_no'];
                            $update['refund_time'] = time();
                            $update['refund_money'] = $res['refund_fee'];
                            $update['liquidated_damages'] = $liquidated_damages;
                            $all_refund_money = bcadd($order['all_refund_money'], $refund_money, 2);
                            $last_all_money = bcsub($order['last_all_money'], $refund_money, 2);
                            if($last_all_money < 0) $last_all_money = 0;
                            if($all_refund_money > $order['all_money']) $all_refund_money = $order['all_money'];
                            $update['all_refund_money'] = $all_refund_money;
                            $update['last_all_money'] = $last_all_money;
                            $update['all_refund_number'] = $order['all_refund_number'] ? $order['all_refund_number'] . ',' . $out_refund_no : $out_refund_no;
                            $result = self::where('id', $order['id'])->update($update);
                            //车状态修改
                            MerchantCar::where('id', $order['merchant_car_id'])->update(['car_status' => 1]);
                            //写入平台流水
                            $platform_log = [
                                'user_id' => $user['id'],
                                'amount' => $order['all_money'],
                                'type' => 3,
                                'log_note' => '取消预约退款',
                                'order_id' => $order['id'],
                                'order_type' => 2,
                                'createtime' => time(),
                                'total_order_id' => $order['id']
                            ];
                            \app\common\model\PlatformLog::insert($platform_log);
                        }else{
                            Db::rollback();
                            $this->error('取消失败');
                        }

                        //换车订单退款
                        $order_change_payed = $order['order_change_payed'];
                        if($order_change_payed){
                            foreach ($order_change_payed as $kc=>$vc){
                                $liquidated_damages = bcmul($cancel_rate, $vc['last_all_money'], 2);
                                $refund_money = bcsub($vc['last_all_money'], $liquidated_damages, 2);
                                $vc['refund_money'] = $refund_money;
                                $update = ['pay_status' => 3, 'cancel_time' => time()];
                                if($vc['deposit_status'] == 1 && $vc['deposit'] > 0){
                                    $update['deposit_status'] = 2;
                                }
                                $out_refund_no = $this->getOutRefundNo('order_change');
                                $vc['out_refund_no'] = $out_refund_no;
                                $res = $this->alipayRefund($vc, $user);
                                if($res['code'] == '10000'){
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['trade_no'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = $res['refund_fee'];
                                    $update['liquidated_damages'] = $liquidated_damages;
                                    $result = \app\admin\model\OrderChange::where('id', $vc['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $vc['refund_money'],
                                        'type' => 7,
                                        'log_note' => '取消预约换车订单退款',
                                        'order_id' => $vc['id'],
                                        'order_type' => 2,
                                        'createtime' => time(),
                                        'total_order_id' => $order['id']
                                    ];
                                    \app\common\model\PlatformLog::insert($platform_log);
                                }else{
                                    Db::rollback();
                                    $this->error('取消失败');
                                }
                            }
                        }

                        //续租订单退款
                        $order_continue_payed = $order['order_continue_payed'];
                        if($order_continue_payed){
                            foreach ($order_continue_payed as $kn=>$vn){
                                $liquidated_damages = bcmul($cancel_rate, $vn['last_all_money'], 2);
                                $refund_money = bcsub($vn['last_all_money'], $liquidated_damages, 2);
                                $vn['refund_money'] = $refund_money;
                                $update = ['pay_status' => 3, 'cancel_time' => time()];
                                if($vn['deposit_status'] == 1 && $vn['deposit'] > 0){
                                    $update['deposit_status'] = 2;
                                }
                                $out_refund_no = $this->getOutRefundNo('order_continue');
                                $vn['out_refund_no'] = $out_refund_no;
                                $res = $this->alipayRefund($vn, $user);
                                if($res['code'] == '10000'){
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['trade_no'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = $res['refund_fee'];
                                    $update['liquidated_damages'] = $liquidated_damages;
                                    $result = \app\admin\model\OrderContinue::where('id', $vn['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $vn['refund_money'],
                                        'type' => 9,
                                        'log_note' => '取消预约续租订单退款',
                                        'order_id' => $vn['id'],
                                        'order_type' => 2,
                                        'createtime' => time(),
                                        'total_order_id' => $order['id']
                                    ];
                                    \app\common\model\PlatformLog::insert($platform_log);
                                }else{
                                    Db::rollback();
                                    $this->error('取消失败');
                                }
                            }
                        }

                        //当面付订单退款
                        $order_face_payed = $order['order_face_payed'];
                        if($order_face_payed){
                            foreach ($order_face_payed as $kf=>$vf){
                                $liquidated_damages = bcmul($cancel_rate, $vf['last_all_money'], 2);
                                $refund_money = bcsub($vf['last_all_money'], $liquidated_damages, 2);
                                $vf['refund_money'] = $refund_money;
                                $update = ['status' => 3, 'cancel_time' => time()];
                                $out_refund_no = $this->getOutRefundNo('order_face');
                                $vf['out_refund_no'] = $out_refund_no;
                                $res = $this->alipayrefund($vf, $user);
                                if($res['code'] == '10000'){
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['trade_no'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = $res['refund_fee'];
                                    $update['liquidated_damages'] = $liquidated_damages;
                                    $result = \app\admin\model\OrderFace::where('id', $vf['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $vf['refund_money'],
                                        'type' => 11,
                                        'log_note' => '取消预约当面付订单退款',
                                        'order_id' => $vf['id'],
                                        'order_type' => 2,
                                        'createtime' => time(),
                                        'total_order_id' => $order['id']
                                    ];
                                    \app\common\model\PlatformLog::insert($platform_log);
                                }else{
                                    Db::rollback();
                                    $this->error('取消失败');
                                }
                            }
                        }
                    }
                }else{//全扣 即不退款
                    //主订单
                    $result = self::where('id', $order['id'])->update(['status' => 4, 'cancel_time' => time()]);
                    //车状态修改
                    MerchantCar::where('id', $order['merchant_car_id'])->update(['car_status' => 1]);
                    //换车订单
                    $order_change_payed = $order['order_change_payed'];
                    $order_change_payed = $order_change_payed->toArray();
                    if($order_change_payed){
                        $change_ids = array_column($order_change_payed, 'id');
                        $result = \app\admin\model\OrderChange::where('id', 'in', implode(',', $change_ids))->update(['pay_status' => 3, 'cancel_time' => time()]);
                    }

                    //续租订单
                    $order_continue_payed = $order['order_continue_payed'];
                    $order_continue_payed = $order_continue_payed->toArray();
                    if($order_continue_payed){
                        $continue_ids = array_column($order_continue_payed, 'id');
                        $result = \app\admin\model\OrderContinue::where('id', 'in', implode(',', $continue_ids))->update(['pay_status' => 3, 'cancel_time' => time()]);
                    }

                    //当面付订单
                    $order_face_payed = $order['order_face_payed'];
                    $order_face_payed = $order_face_payed->toArray();
                    if($order_face_payed){
                        $face_ids = array_column($order_face_payed, 'id');
                        $result = \app\admin\model\OrderFace::where('id', 'in', implode(',', $face_ids))->update(['status' => 3, 'cancel_time' => time()]);
                    }
                }

                //其他无偿换车订单
                $other_change_id = \app\admin\model\OrderChange::where(['is_delete' => 1, 'order_id' => $order['id']])->where('pay_status', 'in', '1,2')->column('id');
                if($other_change_id){
                    \app\admin\model\OrderChange::where('id', 'in', implode(',', $other_change_id))->update(['pay_status' => 3, 'cancel_time' => time()]);
                }

                //其他待支付续租订单
                $other_continue_id = \app\admin\model\OrderContinue::where(['is_delete' => 1, 'order_id' => $order['id']])->where('pay_status', 'in', '1')->column('id');
                if($other_continue_id){
                    \app\admin\model\OrderContinue::where('id', 'in', implode(',', $other_continue_id))->update(['pay_status' => 3, 'cancel_time' => time()]);
                }

                //其他待支付当面付订单
                $other_face_id = \app\admin\model\OrderFace::where(['is_delete' => 1, 'order_id' => $order['id']])->where('status', 'in', '1')->column('id');
                if($other_face_id){
                    \app\admin\model\OrderFace::where('id', 'in', implode(',', $other_face_id))->update(['status' => 3, 'cancel_time' => time()]);
                }

                $merchant_car = \app\api\model\MerchantCar::where(['is_delete' => 1, 'id' => $order['merchant_car_id']])->find();
                $merchant_phone = \app\api\model\Merchant::where(['is_delete' => 1, 'id' => $order['merchant_id']])->value('merchant_phone');
                if($merchant_phone && $merchant_car){
                    $car_cate = CarCate::where('id', $merchant_car['type_id'])->value('cate_name');
                    //向商家发送短信
                    $data = [
                        'number' => $order['out_trade_no'],
                        'model' => $car_cate,
                        'car_number' => $order['car_number'],
                        'username' => $user['truename'],
                        'start_time' => date('Y-m-d H:i:s', $order['start_time']),
                        'pick_address' => $order['pick_address'],
                    ];
                    $res = sendMsg($merchant_phone, $data, 'SMS_464111297');
                    //向用户发送短信
                    $service_phone = \app\common\model\Config::where('name', 'service_phone')->value('value');
                    $data = [
                        'type' => $car_cate,
                        'service' => $service_phone,
                    ];
                    $res = sendMsg($order['user_phone'], $data, 'SMS_464760133');
                }
            }
            Db::commit();
            $this->success('取消订单成功！');
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 退押金
     */
    public function deposit()
    {
        $ids = $this->request->param('ids');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->where('id', 'in', $ids)->select();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        foreach ($row as $val){
            if($val['deposit'] == 0){
                $this->error(__('有无押金订单'));
            }
            if($val['status'] != 3){
                $this->error(__('有非已完成状态的订单'));
            }
            if($val['deposit_status'] != 1){
                $this->error(__('有订单押金状态是非待退还状态'));
            }
        }
        Db::startTrans();
        try {
            $user_model = new User();
            $platform_log = [];
            foreach ($row as $key=>$value){
                $update = ['deposit_status' => 2];
                $out_refund_no = OrderModel::getOutRefundNo();
                $value['out_refund_no'] = $out_refund_no;
                $user = \app\admin\model\User::where('id', $value['user_id'])->find();
                if($user['user_type'] == 1){
                    //微信退款
                    $res = $this->wechatRefund($value, $user, 2);
                    if($res['return_code'] == 'SUCCESS' && $res['result_code']=='SUCCESS'){
                        $update['out_refund_no'] = $out_refund_no;
                        $update['refund_id'] = $res['refund_id'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                        //更新订单
                        $res = $this->model->where('id', $value['id'])->update($update);
                        if($res){
                            $platform_log[] = [
                                'user_id' => $value['user_id'],
                                'amount' => $value['deposit'],
                                'type' => 4,
                                'log_note' => '押金退款',
                                'order_id' => $value['id'],
                                'order_type' => 1,
                                'createtime' => time(),
                            ];
                        }
                    }
                }else{
                    //支付宝退款
                    $res = $this->alipayRefund($value, $user, 2);
                    if($res['code'] == '10000'){
                        $update['out_refund_no'] = $value['out_refund_no'];
                        $update['refund_id'] = $res['trade_no'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = $res['refund_fee'];
                        $res = $this->model->where('id', $value['id'])->update($update);

                        if($res){
                            $platform_log[] = [
                                'user_id' => $value['user_id'],
                                'amount' => $value['deposit'],
                                'type' => 4,
                                'log_note' => '押金退款',
                                'order_id' => $value['id'],
                                'order_type' => 1,
                                'createtime' => time(),
                            ];
                        }
                    }
                }

            }
            //写入平台流水
            if($platform_log){
                \app\common\model\PlatformLog::insertAll($platform_log);
            }
            Db::commit();
            $this->success('退押金成功！');
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 取车
     */
    public function pick($ids)
    {
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['status'] != 1){
            $text = \app\common\model\Order::fetchStatus($row['status']);
            $this->error('订单'.$text);
        }
        $merchant_car = MerchantCar::with('cars')->where(['is_delete' => 1, 'id' => $row['merchant_car_id']])->find();
        if(!$merchant_car){
            $this->error('商家车辆不存在');
        }
        if($this->request->isPost()){
            Db::startTrans();
            try {
                $params = $this->request->post('row/a');
                if(!$params){
                    $this->error(__('Parameter %s can not be empty', ''));
                }
                if(!$params['start_check_video'] && !$params['start_check_images']){
                    $this->error('取车验车视频和取车验车图片必须至少上传一个');
                }
                $params['pick_time'] = time();
                $params['status'] = 2;
                $res = $row->save($params);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($res){
                $this->success('取车成功');
            }else{
                $this->error('取车失败');
            }
        }
        $this->view->assign('row', $row);
        $this->view->assign('merchant_car', $merchant_car);
        return $this->view->fetch();
    }

    /**
     * 还车
     */
    public function return($ids)
    {
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row['status'] != 2){
            $text = \app\common\model\Order::fetchStatus($row['status']);
            $this->error('订单'.$text);
        }
        $merchant_car = MerchantCar::with('cars')->where(['is_delete' => 1, 'id' => $row['merchant_car_id']])->find();
        if(!$merchant_car){
            $this->error('商家车辆不存在');
        }
        if($this->request->isPost()){
            Db::startTrans();
            try {
                $params = $this->request->post('row/a');
                if(!$params){
                    $this->error(__('Parameter %s can not be empty', ''));
                }
                if(!$params['end_check_video'] && !$params['end_check_images']){
                    $this->error('还车验车视频和取车验车图片必须至少上传一个');
                }
                $params['return_time'] = time();
                $params['status'] = 3;
                if(isset($params['real_return_time']) && $params['real_return_time']){
                    $params['real_return_time'] = strtotime($params['real_return_time']);
                }
                $res = $row->save($params);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if($res){
                $this->success('还车成功');
            }else{
                $this->error('还车失败');
            }
        }
        $this->view->assign('row', $row);
        $this->view->assign('merchant_car', $merchant_car);
        return $this->view->fetch();
    }

    /**
     * 换车退款申请审核
     */
    public function examine()
    {
        $ids = $this->request->param('ids');
        $type = $this->request->param('type');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //换车总退款申请订单
        $order_refund = \app\admin\model\OrderRefund::where(['is_delete' => 1, 'order_id' => $ids, 'user_id' => $row['user_id']])->find();
        if(!$order_refund){
            $this->error('退款申请不存在');
        }
        Db::startTrans();
        try {
            if($type == 1){//通过
                $user = \app\admin\model\User::where('id', $order_refund['user_id'])->find();
                $update = ['status' => 2, 'updatetime' => time()];
                if($row['pay_type'] == 1){
                    //微信小程序打款
                    $res = $this->wechatPay($order_refund, $user);
                    if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                        $update['transaction_id'] = $res['payment_no'];
                        $update['time_end'] = $res['payment_time'];
                        $update['total_fee'] = $order_refund['all_money'];
                        $platform_log = [
                            'user_id' => $row['user_id'],
                            'amount' => $order_refund['all_money'],
                            'type' => 14,
                            'log_note' => '换车总退款打款',
                            'order_id' => $order_refund['id'],
                            'order_type' => 1,
                            'createtime' => time(),
                            'total_order_id' => $row['id']
                        ];
                        $platform_log_model = new \app\common\model\PlatformLog();
                        $platform_log_model->save($platform_log);
                        $res = \app\admin\model\OrderRefund::where('id', $order_refund['id'])->update($update);
                    }else{
                        Db::rollback();
                        $this->error('退款失败');
                    }
                }else{
                    //支付宝小程序打款
                    $res = $this->alipay($order_refund, $user);
                    if(!empty($res->code) && $res->code==10000) {
                        $update['transaction_id'] = $res->order_id;
                        $update['time_end'] = strtotime($res->trans_date);
                        $update['total_fee'] = $order_refund['all_money'];
                        $platform_log = [
                            'user_id' => $row['user_id'],
                            'amount' => $order_refund['all_money'],
                            'type' => 14,
                            'log_note' => '换车总退款打款',
                            'order_id' => $order_refund['id'],
                            'order_type' => 1,
                            'createtime' => time(),
                            'total_order_id' => $row['id']
                        ];
                        $platform_log_model = new \app\common\model\PlatformLog();
                        $platform_log_model->save($platform_log);
                        $res = \app\admin\model\OrderRefund::where('id', $order_refund['id'])->update($update);
                    }else{
                        Db::rollback();
                        $this->error('退款失败');
                    }
                }
            }else{//拒绝
                \app\admin\model\OrderRefund::where(['is_delete' => 1, 'order_id' => $order_refund['id']])->update(['status' => 3, 'updatetime' => time()]);
                \app\admin\model\Order::where('id', $ids)->update(['refund_status' => 4]);
            }
            Db::commit();
            $this->success('审核成功！');
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 订单退款申请审核
     */
    public function refund()
    {
        $ids = $this->request->param('ids');
        $type = $this->request->param('type');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->with(['order_change_payed', 'order_continue_payed', 'order_face_payed'])->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        if($row['status'] != 3){
            $text = \app\common\model\Order::fetchStatus($row['status']);
            $this->error('订单' . $text);
        }
        if($row['order_refund_status'] != 2){
            $text = \app\common\model\Order::fetchOrderRefundStatus($row['order_refund_status']);
            $this->error('订单退款' . $text);
        }
        $order_all_money = $row['last_all_money'];
        if($row['order_change_payed']){
            $change_last_all_money = array_column($row['order_change_payed'], 'last_all_money');
            $change_last_all_money = array_sum($change_last_all_money);
            $order_all_money = bcadd($order_all_money, $change_last_all_money, 2);
        }
        if($row['order_continue_payed']){
            $continue_last_all_money = array_column($row['orderContinuePayed'], 'last_all_money');
            $continue_last_all_money = array_sum($continue_last_all_money);
            $order_all_money = bcadd($order_all_money, $continue_last_all_money, 2);
        }
        if($row['order_face_payed']){
            $face_last_all_money = array_column($row['orderFacePayed'], 'last_all_money');
            $face_last_all_money = array_sum($face_last_all_money);
            $order_all_money = bcadd($order_all_money, $face_last_all_money, 2);
        }
        $rate = $row['order_refund_money'] / $order_all_money;
        Db::startTrans();
        try {
            $user = User::where('id', $row['user_id'])->find();
            if($type == 1){//通过
                if($row['pay_type'] == 1){//微信
                    //主订单退款
                    if($row['order_refund_money'] <= $row['last_all_money']){
                        $refund_money = $row['order_refund_money'];
                        $last_money = 0;
                    }else{
                        $refund_money = $row['last_all_money'];
                        $last_money = bcsub($row['order_refund_money'], $row['last_all_money'], 2);
                    }
                    $row['refund_money'] = $refund_money;
                    $update = ['order_refund_time' => time(), 'order_refund_status' => 3];
                    $out_refund_no = $this->getOutRefundNo();
                    $row['out_refund_no'] = $out_refund_no;
                    $res = $this->wechatRefund($row, $user);
                    if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                        $update['out_refund_no'] = $out_refund_no;
                        $update['refund_id'] = $res['refund_id'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                        $all_refund_money = bcadd($row['all_refund_money'], $refund_money, 2);
                        $last_all_money = bcsub($row['last_all_money'], $refund_money, 2);
                        if($last_all_money < 0) $last_all_money = 0;
                        if($all_refund_money > $row['all_money']) $all_refund_money = $row['all_money'];
                        $update['all_refund_money'] = $all_refund_money;
                        $update['last_all_money'] = $last_all_money;
                        $update['all_refund_number'] = $row['all_refund_number'] ? $row['all_refund_number'] . ',' . $out_refund_no : $out_refund_no;
                        $result = $this->model->where('id', $ids)->update($update);
                        //写入平台流水
                        $platform_log = [
                            'user_id' => $user['id'],
                            'amount' => $refund_money,
                            'type' => 3,
                            'log_note' => '订单退款',
                            'order_id' => $ids,
                            'order_type' => 1,
                            'createtime' => time(),
                        ];
                        PlatformLog::insert($platform_log);
                    }else{
                        Db::rollback();
                        return ['status' => 0, 'message' => '退款失败', 'result' => ''];
                    }

                    //换车订单退款
                    $order_change_payed = $row['order_change_payed'];
                    if($last_money > 0 && $order_change_payed){
                        foreach ($order_change_payed as $key=>$value){
                            if($last_money > 0){
                                if($last_money <= $value['last_all_money']){
                                    $refund_money = $last_money;
                                    $last_money = 0;
                                }else{
                                    $refund_money = $value['last_all_money'];
                                    $last_money = bcsub($last_money, $value['last_all_money'], 2);
                                }
                                $value['refund_money'] = $refund_money;
                                $update = ['pay_status' => 4];
                                $out_refund_no = $this->getOutRefundNo('order_change');
                                $value['out_refund_no'] = $out_refund_no;
                                $res = $this->wechatRefund($value, $user);
                                if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['refund_id'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                    $all_refund_money = bcadd($value['all_refund_money'], $refund_money, 2);
                                    $last_all_money = bcsub($value['last_all_money'], $refund_money, 2);
                                    if($last_all_money < 0) $last_all_money = 0;
                                    if($all_refund_money > $value['all_money']) $all_refund_money = $value['all_money'];
                                    $update['all_refund_money'] = $all_refund_money;
                                    $update['last_all_money'] = $last_all_money;
                                    $result = OrderChange::where('id', $value['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $value['refund_money'],
                                        'type' => 7,
                                        'log_note' => '换车订单退款',
                                        'order_id' => $value['id'],
                                        'order_type' => 1,
                                        'createtime' => time(),
                                        'total_order_id' => $ids
                                    ];
                                    PlatformLog::insert($platform_log);
                                }else{
                                    Db::rollback();
                                    return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                                }
                            }
                        }
                    }

                    //续租订单退款
                    $order_continue_payed = $row['order_continue_payed'];
                    if($last_money > 0 && $order_continue_payed){
                        foreach ($order_continue_payed as $k=>$v){
                            if($last_money > 0){
                                if($last_money <= $v['last_all_money']){
                                    $refund_money = $last_money;
                                    $last_money = 0;
                                }else{
                                    $refund_money = $v['last_all_money'];
                                    $last_money = bcsub($last_money, $v['last_all_money'], 2);
                                }
                                $v['refund_money'] = $refund_money;
                                $update = ['pay_status' => 4];
                                $out_refund_no = $this->getOutRefundNo('order_continue');
                                $v['out_refund_no'] = $out_refund_no;
                                $res = $this->wechatRefund($v, $user);
                                if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['refund_id'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                    $all_refund_money = bcadd($v['all_refund_money'], $refund_money, 2);
                                    $last_all_money = bcsub($v['last_all_money'], $refund_money, 2);
                                    if($last_all_money < 0) $last_all_money = 0;
                                    if($all_refund_money > $v['all_money']) $all_refund_money = $v['all_money'];
                                    $update['all_refund_money'] = $all_refund_money;
                                    $update['last_all_money'] = $last_all_money;
                                    $result = OrderContinue::where('id', $v['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $v['refund_money'],
                                        'type' => 9,
                                        'log_note' => '续租订单退款',
                                        'order_id' => $v['id'],
                                        'order_type' => 1,
                                        'createtime' => time(),
                                        'total_order_id' => $ids
                                    ];
                                    PlatformLog::insert($platform_log);
                                }else{
                                    Db::rollback();
                                    return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                                }
                            }
                        }
                    }

                    //当面付订单退款
                    $order_face_payed = $row['order_face_payed'];
                    if($last_money > 0 && $order_face_payed){
                        foreach ($order_face_payed as $kk=>$vv){
                            if($last_money > 0) {
                                if ($last_money <= $vv['last_all_money']) {
                                    $refund_money = $last_money;
                                    $last_money = 0;
                                } else {
                                    $refund_money = $vv['last_all_money'];
                                    $last_money = bcsub($last_money, $vv['last_all_money'], 2);
                                }
                                $vv['refund_money'] = $refund_money;
                                $update = ['pay_status' => 4];
                                $out_refund_no = $this->getOutRefundNo('order_face');
                                $vv['out_refund_no'] = $out_refund_no;
                                $res = $this->wechatRefund($vv, $user);
                                if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['refund_id'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                    $all_refund_money = bcadd($vv['all_refund_money'], $refund_money, 2);
                                    $last_all_money = bcsub($vv['last_all_money'], $refund_money, 2);
                                    if ($last_all_money < 0) $last_all_money = 0;
                                    if ($all_refund_money > $vv['all_money']) $all_refund_money = $vv['all_money'];
                                    $update['all_refund_money'] = $all_refund_money;
                                    $update['last_all_money'] = $last_all_money;
                                    $result = OrderFace::where('id', $vv['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $vv['refund_money'],
                                        'type' => 11,
                                        'log_note' => '当面付订单退款',
                                        'order_id' => $vv['id'],
                                        'order_type' => 1,
                                        'createtime' => time(),
                                        'total_order_id' => $ids
                                    ];
                                    PlatformLog::insert($platform_log);
                                } else {
                                    Db::rollback();
                                    return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                                }
                            }
                        }
                    }
                }
                //商家退余额
                $balance_log = \app\common\model\BalanceLog::where(['merchant_id' => $row['merchant_id'], 'order_id' => $ids, 'type' => 1, 'order_type' => 1])->find();
                if($balance_log){
                    $refund_balance = bcmul($balance_log['amount'], $rate, 2);
                    if($refund_balance > 0){
                        //商家余额减少
                        \app\common\model\Merchant::where('id', $row['merchant_id'])->dec('shop_balance', $refund_balance)->update();
                        $balance_log = [
                            'merchant_id' => $row['merchant_id'],
                            'amount' => -$refund_balance,
                            'type' => 7,
                            'log_note' => '预约订单退款退余额',
                            'createtime' => time(),
                            'order_id' => $ids,
                            'order_type' => 1,
                            'total_order_id' => $ids
                        ];
                        \app\common\model\BalanceLog::insert($balance_log);
                    }
                }
                //上级分销退余额
                $parent_id = $user['parent_id']??0;
                if($parent_id){
                    $parent = User::where('id', $parent_id)->find();
                    $user_money_log = \app\admin\model\UserMoneyLog::where(['user_id' => $parent_id, 'order_id' => $ids, 'type' => 1, 'source_uid' => $user['id']])->find();
                    if($user_money_log && $parent){
                        $user_refund_money = bcmul($user_money_log['money'], $rate, 2);
                        if($user_refund_money > 0){
                            User::where('id', $parent_id)->dec('money', $user_refund_money)->update();
                            $new_money = bcsub($parent['money'], $user_refund_money, 2);
                            $user_money_log = [
                                'user_id' => $parent_id,
                                'money' => $user_refund_money,
                                'before' => $parent['money'],
                                'after' => $new_money,
                                'memo' => '订单退款扣除',
                                'createtime' => time(),
                                'order_id' => $ids,
                                'type' => 6,
                                'source_uid' => $user['id'],
                            ];
                            \app\admin\model\UserMoneyLog::insert($user_money_log);
                            //用户分销表减少金额
                            $user_income = \app\admin\model\UserIncome::where(['user_id' => $parent_id, 'source_uid' => $user['id'], 'order_id' => $ids, 'type' => 2])->find();
                            if($user_income){
                                $income_refund_money = bcmul($user_income['amount'], $rate, 2);
                                $new_money = bcsub($user_income['amount'], $income_refund_money, 2);
                                \app\admin\model\UserIncome::where('id', $user_income['id'])->update(['amount' => $new_money]);
                            }
                        }
                    }
                }
            }else{//拒绝
                \app\admin\model\Order::where('id', $ids)->update(['order_refund_status' => 4, 'updatetime' => time()]);
            }
            Db::commit();
            $this->success('审核成功！');
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 订单退款
     */
    public function giveback()
    {
        $ids = $this->request->param('ids');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->with(['order_change_payed', 'order_continue_payed', 'order_face_payed'])->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        if($row['status'] != 3){
            $text = \app\common\model\Order::fetchStatus($row['status']);
            $this->error('订单' . $text);
        }
        if($row['order_refund_status'] == 2 || $row['order_refund_status'] == 3){
            $text = \app\common\model\Order::fetchOrderRefundStatus($row['order_refund_status']);
            $this->error('订单退款' . $text);
        }
        $order_all_money = $row['last_all_money'];
        if($row['order_change_payed']){
            $change_last_all_money = array_column($row['order_change_payed'], 'last_all_money');
            $change_last_all_money = array_sum($change_last_all_money);
            $order_all_money = bcadd($order_all_money, $change_last_all_money, 2);
        }
        if($row['order_continue_payed']){
            $continue_last_all_money = array_column($row['orderContinuePayed'], 'last_all_money');
            $continue_last_all_money = array_sum($continue_last_all_money);
            $order_all_money = bcadd($order_all_money, $continue_last_all_money, 2);
        }
        if($row['order_face_payed']){
            $face_last_all_money = array_column($row['orderFacePayed'], 'last_all_money');
            $face_last_all_money = array_sum($face_last_all_money);
            $order_all_money = bcadd($order_all_money, $face_last_all_money, 2);
        }
        if($this->request->isPost()){
            Db::startTrans();
            try {
                $params = $this->request->post('row/a');
                if(!$params){
                    $this->error(__('Parameter %s can not be empty', ''));
                }
                $rate = $params['money'] / $order_all_money;
                $user = User::where('id', $row['user_id'])->find();
                if($row['pay_type'] == 1){//微信
                    //主订单退款
                    if($params['money'] <= $row['last_all_money']){
                        $refund_money = $params['money'];
                        $last_money = 0;
                    }else{
                        $refund_money = $row['last_all_money'];
                        $last_money = bcsub($params['money'], $row['last_all_money'], 2);
                    }
                    $row['refund_money'] = $refund_money;
                    $update = ['order_refund_time' => time(), 'order_refund_status' => 3, 'order_refund_money' => $params['money']];
                    $out_refund_no = $this->getOutRefundNo();
                    $row['out_refund_no'] = $out_refund_no;
                    $res = $this->wechatRefund($row, $user);
                    if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                        $update['out_refund_no'] = $out_refund_no;
                        $update['refund_id'] = $res['refund_id'];
                        $update['refund_time'] = time();
                        $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                        $all_refund_money = bcadd($row['all_refund_money'], $refund_money, 2);
                        $last_all_money = bcsub($row['last_all_money'], $refund_money, 2);
                        if($last_all_money < 0) $last_all_money = 0;
                        if($all_refund_money > $row['all_money']) $all_refund_money = $row['all_money'];
                        $update['all_refund_money'] = $all_refund_money;
                        $update['last_all_money'] = $last_all_money;
                        $update['all_refund_number'] = $row['all_refund_number'] ? $row['all_refund_number'] . ',' . $out_refund_no : $out_refund_no;
                        $result = $this->model->where('id', $ids)->update($update);
                        //写入平台流水
                        $platform_log = [
                            'user_id' => $user['id'],
                            'amount' => $refund_money,
                            'type' => 3,
                            'log_note' => '订单退款',
                            'order_id' => $ids,
                            'order_type' => 1,
                            'createtime' => time(),
                        ];
                        PlatformLog::insert($platform_log);
                    }else{
                        Db::rollback();
                        return ['status' => 0, 'message' => '退款失败', 'result' => ''];
                    }


                    //换车订单退款
                    $order_change_payed = $row['order_change_payed'];
                    if($last_money > 0 && $order_change_payed){
                        foreach ($order_change_payed as $key=>$value){
                            if($last_money > 0){
                                if($last_money <= $value['last_all_money']){
                                    $refund_money = $last_money;
                                    $last_money = 0;
                                }else{
                                    $refund_money = $value['last_all_money'];
                                    $last_money = bcsub($last_money, $value['last_all_money'], 2);
                                }
                                $value['refund_money'] = $refund_money;
                                $update = ['pay_status' => 4];
                                $out_refund_no = $this->getOutRefundNo('order_change');
                                $value['out_refund_no'] = $out_refund_no;
                                $res = $this->wechatRefund($value, $user);
                                if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['refund_id'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                    $all_refund_money = bcadd($value['all_refund_money'], $refund_money, 2);
                                    $last_all_money = bcsub($value['last_all_money'], $refund_money, 2);
                                    if($last_all_money < 0) $last_all_money = 0;
                                    if($all_refund_money > $value['all_money']) $all_refund_money = $value['all_money'];
                                    $update['all_refund_money'] = $all_refund_money;
                                    $update['last_all_money'] = $last_all_money;
                                    $result = OrderChange::where('id', $value['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $value['refund_money'],
                                        'type' => 7,
                                        'log_note' => '换车订单退款',
                                        'order_id' => $value['id'],
                                        'order_type' => 1,
                                        'createtime' => time(),
                                        'total_order_id' => $ids
                                    ];
                                    PlatformLog::insert($platform_log);
                                }else{
                                    Db::rollback();
                                    return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                                }
                            }
                        }
                    }

                    //续租订单退款
                    $order_continue_payed = $row['order_continue_payed'];
                    if($last_money > 0 && $order_continue_payed){
                        foreach ($order_continue_payed as $k=>$v){
                            if($last_money > 0){
                                if($last_money <= $v['last_all_money']){
                                    $refund_money = $last_money;
                                    $last_money = 0;
                                }else{
                                    $refund_money = $v['last_all_money'];
                                    $last_money = bcsub($last_money, $v['last_all_money'], 2);
                                }
                                $v['refund_money'] = $refund_money;
                                $update = ['pay_status' => 4];
                                $out_refund_no = $this->getOutRefundNo('order_continue');
                                $v['out_refund_no'] = $out_refund_no;
                                $res = $this->wechatRefund($v, $user);
                                if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['refund_id'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                    $all_refund_money = bcadd($v['all_refund_money'], $refund_money, 2);
                                    $last_all_money = bcsub($v['last_all_money'], $refund_money, 2);
                                    if($last_all_money < 0) $last_all_money = 0;
                                    if($all_refund_money > $v['all_money']) $all_refund_money = $v['all_money'];
                                    $update['all_refund_money'] = $all_refund_money;
                                    $update['last_all_money'] = $last_all_money;
                                    $result = OrderContinue::where('id', $v['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $v['refund_money'],
                                        'type' => 9,
                                        'log_note' => '续租订单退款',
                                        'order_id' => $v['id'],
                                        'order_type' => 1,
                                        'createtime' => time(),
                                        'total_order_id' => $ids
                                    ];
                                    PlatformLog::insert($platform_log);
                                }else{
                                    Db::rollback();
                                    return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                                }
                            }
                        }
                    }

                    //当面付订单退款
                    $order_face_payed = $row['order_face_payed'];
                    if($last_money > 0 && $order_face_payed){
                        foreach ($order_face_payed as $kk=>$vv){
                            if($last_money > 0) {
                                if ($last_money <= $vv['last_all_money']) {
                                    $refund_money = $last_money;
                                    $last_money = 0;
                                } else {
                                    $refund_money = $vv['last_all_money'];
                                    $last_money = bcsub($last_money, $vv['last_all_money'], 2);
                                }
                                $vv['refund_money'] = $refund_money;
                                $update = ['pay_status' => 4];
                                $out_refund_no = $this->getOutRefundNo('order_face');
                                $vv['out_refund_no'] = $out_refund_no;
                                $res = $this->wechatRefund($vv, $user);
                                if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
                                    $update['out_refund_no'] = $out_refund_no;
                                    $update['refund_id'] = $res['refund_id'];
                                    $update['refund_time'] = time();
                                    $update['refund_money'] = bcdiv($res['refund_fee'], 100, 2);
                                    $all_refund_money = bcadd($vv['all_refund_money'], $refund_money, 2);
                                    $last_all_money = bcsub($vv['last_all_money'], $refund_money, 2);
                                    if ($last_all_money < 0) $last_all_money = 0;
                                    if ($all_refund_money > $vv['all_money']) $all_refund_money = $vv['all_money'];
                                    $update['all_refund_money'] = $all_refund_money;
                                    $update['last_all_money'] = $last_all_money;
                                    $result = OrderFace::where('id', $vv['id'])->update($update);
                                    //写入平台流水
                                    $platform_log = [
                                        'user_id' => $user['id'],
                                        'amount' => $vv['refund_money'],
                                        'type' => 11,
                                        'log_note' => '当面付订单退款',
                                        'order_id' => $vv['id'],
                                        'order_type' => 1,
                                        'createtime' => time(),
                                        'total_order_id' => $ids
                                    ];
                                    PlatformLog::insert($platform_log);
                                } else {
                                    Db::rollback();
                                    return ['status' => 0, 'message' => '取消失败', 'result' => ''];
                                }
                            }
                        }
                    }
                }
                //商家退余额
                $balance_log = \app\common\model\BalanceLog::where(['merchant_id' => $row['merchant_id'], 'order_id' => $ids, 'type' => 1, 'order_type' => 1])->find();
                if($balance_log){
                    $refund_balance = bcmul($balance_log['amount'], $rate, 2);
                    if($refund_balance > 0){
                        //商家余额减少
                        \app\common\model\Merchant::where('id', $row['merchant_id'])->dec('shop_balance', $refund_balance)->update();
                        $balance_log = [
                            'merchant_id' => $row['merchant_id'],
                            'amount' => -$refund_balance,
                            'type' => 7,
                            'log_note' => '预约订单退款退余额',
                            'createtime' => time(),
                            'order_id' => $ids,
                            'order_type' => 1,
                            'total_order_id' => $ids
                        ];
                        \app\common\model\BalanceLog::insert($balance_log);
                    }
                }
                //上级分销退余额
                $parent_id = $user['parent_id']??0;
                if($parent_id){
                        $parent = User::where('id', $parent_id)->find();
                        $user_money_log = \app\admin\model\UserMoneyLog::where(['user_id' => $parent_id, 'order_id' => $ids, 'type' => 1, 'source_uid' => $user['id']])->find();
                        if($user_money_log && $parent){
                            $user_refund_money = bcmul($user_money_log['money'], $rate, 2);
                            if($user_refund_money > 0){
                                User::where('id', $parent_id)->dec('money', $user_refund_money)->update();
                                $new_money = bcsub($parent['money'], $user_refund_money, 2);
                                $user_money_log = [
                                    'user_id' => $parent_id,
                                    'money' => $user_refund_money,
                                    'before' => $parent['money'],
                                    'after' => $new_money,
                                    'memo' => '订单退款扣除',
                                    'createtime' => time(),
                                    'order_id' => $ids,
                                    'type' => 6,
                                    'source_uid' => $user['id'],
                                ];
                                \app\admin\model\UserMoneyLog::insert($user_money_log);
                                //用户分销表减少金额
                                $user_income = \app\admin\model\UserIncome::where(['user_id' => $parent_id, 'source_uid' => $user['id'], 'order_id' => $ids, 'type' => 2])->find();
                                if($user_income){
                                    $income_refund_money = bcmul($user_income['amount'], $rate, 2);
                                    $new_money = bcsub($user_income['amount'], $income_refund_money, 2);
                                    \app\admin\model\UserIncome::where('id', $user_income['id'])->update(['amount' => $new_money]);
                                }
                            }
                        }
                    }
                Db::commit();
                $this->success('审核成功！');
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $this->view->assign('row', $row);
        return $this->view->fetch();
    }


    //微信退款
    public function wechatRefund($order, $user, $type = 1){
        $refundFee = $type == 1 ? $order['refund_money']*100 : $order['deposit']*100;
        $refundDesc = $type == 1 ? '取消订单退款' : '押金退款';
        $config = Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $result = $app->refund->byOutTradeNumber($order['out_trade_no'], $order['out_refund_no'], $order['all_money']*100, $refundFee, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => $refundDesc,
        ]);
        return $result;
    }

    //支付宝退款
    public function alipayRefund($order, $user, $type = 1){
        $refundFee = $type == 1 ? $order['refund_money'] : $order['deposit'];
        alipayFactory::setOptions(getOption());
        $result = alipayFactory::payment()->common()->refund($order['out_trade_no'], $refundFee);
        if(!$result){
            return false;
        }
        if($result->code != 10000){
            return false;
            $result->msg."，".$result->sub_msg.PHP_EOL;
        }
        $return_result = json_decode($result->httpBody, true);
        return $return_result['alipay_trade_refund_response'];
    }

    //生成唯一退款号
    public function getOutRefundNo($table = 'order'){
        $out_refund_no = sys_create_orderno(4);
        $order = Db::name($table)->where('out_refund_no', $out_refund_no)->count();
        if($order){
            $this->getOutRefundNo();
        }
        return $out_refund_no;
    }

    //微信小程序付款到零钱
    public function wechatPay($order, $user){
        $config = \think\facade\Config::get('config_wechat.wechat_pay');
        $amount = bcmul($order['all_money'], 100, 0);
        $app = Factory::payment($config);
        $result = $app->transfer->toBalance([
            'partner_trade_no' => $order['out_refund_no'], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $user['openid'],
            'check_name' => 'FORCE_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name' => $user['truename'], // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => $amount, // 企业付款金额，单位为分
            'desc' => '换车总退款打款', // 企业付款操作说明信息。必填
        ]);
        return $result;
    }

    //支付宝小程序转账到个人余额
    public function alipay($order, $user){
        $amount = $order['all_money'];
        $root_path = root_path();
        $alipay_config = config("config_alipay.alipay");//正式
//        $alipay_config = config("config_alipay.alipay_test");//沙箱
        $alipayConfig = new AlipayConfig();
        $alipayConfig->setPrivateKey($alipay_config['privateKey']);
        $alipayConfig->setServerUrl($alipay_config['server_url']);
        $alipayConfig->setAppId($alipay_config['app_id']);
        $alipayConfig->setCharset($alipay_config['charset']);
        $alipayConfig->setSignType($alipay_config['sign_type']);
//        $alipayConfig->setEncryptKey("");
        $alipayConfig->setFormat($alipay_config['format']);
        $alipayConfig->setAppCertPath($root_path.$alipay_config['app_public_cert_path']);
        $alipayConfig->setAlipayPublicCertPath($root_path.$alipay_config['alipay_public_cert_path']);
        $alipayConfig->setRootCertPath($root_path.$alipay_config['alipay_root_cert_path']);
        $alipayClient = new AopCertClient($alipayConfig);
        $alipayClient->isCheckAlipayPublicCert = true;
        $request = new AlipayFundTransUniTransferRequest();
        //业务请求参数
        $bizcontent = json_encode(['out_biz_no'=>$order['out_refund_no'] ,'trans_amount'=>$amount,'product_code'=>'TRANS_ACCOUNT_NO_PWD','biz_scene'=>'DIRECT_TRANSFER','order_title'=>'换车总退款打款' , 'payee_info' => ['identity' => $user['alipayid'], 'identity_type' => 'ALIPAY_USER_ID', 'name' => $user['truename']]], JSON_UNESCAPED_UNICODE);
        $request->setBizContent($bizcontent);
        $responseResult = $alipayClient->execute($request);
        $responseApiName = str_replace(".","_",$request->getApiMethodName())."_response";
        $response = $responseResult->$responseApiName;
        return $response;
    }

    /**
     * 商家车辆保险列表
     */
    public function insure()
    {
        $params = $this->request->param();
        dump($params);die;
    }


}
